const log4js = require('../../../../utils/logUtils');
const logger = log4js.getLogger('sip');
const fxp = require("fast-xml-parser");
const aliveHandler = require("../aliveHandler");
const sip = require("sip");
const deviceCache = require("../../../../db/deviceCache");
const util = require("../../../../utils/stringUtils");
const sipUtils = require("../../../../utils/sipUtils");
const config = require("../../../../db/config");
const clientUtils = require("../clientUtils");

module.exports={
    async handle(rq){
        const content = fxp.parse(rq.content);
        if (content.Query.CmdType === 'Catalog') {
            logger.info('订阅到的内容', content);
            await this.subscribeAck(rq, content);
            await this.notify(rq, content);
        }
        aliveHandler.INTERVAL_CHANNEL(content);
    },
    async subscribeAck(req, content) {
        const {upwardUri, self_account } = await clientUtils.generateClientParams();
        sip.send({
            method: 'INFO',
            status: 200, reason: 'OK',
            uri: upwardUri, version: config.sip.version,
            headers: {
                from: {uri: deviceCache.localUri, params: {tag: sipUtils.rstring()}},
                to: {uri: deviceCache.localUri},
                'call-id': sipUtils.rstring(),
                cseq: req.headers.cseq,
                'expires': '3600', 'Max-Forwards': 70
            }
        }, function (ret) {
            logger.info('subscribe ack', ret);
        });
    },
    async notify(req, content) {
        const that = this;
        const {upwardUri, upward } = await clientUtils.generateClientParams();
        const deviceXml = this.getResponseXml(upward.upper_account);
        sip.send({
            uri: upwardUri, version: config.sip.version,
            headers: {
                from: {uri: deviceCache.localUri, params: {tag: sipUtils.rstring()}},
                to: {uri: deviceCache.localUri},
                'call-id': sipUtils.rstring(),
                cseq: req.headers.cseq,
                Event: 'presence',
                via: req.headers.via,
                'expires': '3600',
                'Max-Forwards': 70,
                'Content-Type': 'Application/MANSCDP+xml',
                contact: '<sip:' + upward.self_account + '@' + config.localIp + ':' + upward.self_port + '>',
            },
            content: '<?xml version="1.0" encoding="GB2312" ?>' +
                '<Response>' +
                '<CmdType>Catalog</CmdType>' +
                '<SN>' + content.Query.SN + '</SN>' +
                '<DeviceID>' + upward.upper_account + '</DeviceID>' +
                '<SumNum>' + deviceCache.cameras.length + '</SumNum>' +
                deviceXml +
                '</Response>'
        }, function (ret) {
            if (ret.status === 200) {
                that.endTalk(req);
            } else {
                logger.info(ret);
            }
        });
    },

    /**
     * 400 停止一个subscribe会话
     * @param {*} req
     */
    async endTalk(req) {
        const {upwardUri, self_account } = await clientUtils.generateClientParams();
        sip.send({
            method: 'INFO',
            status: 400, reason: 'OK',
            uri: upwardUri, version: config.sip.VERSION,
            headers: {
                from: {uri: deviceCache.localUri, params: {tag: sipUtils.rstring()}},
                to: {uri: deviceCache.localUri},
                'call-id': sipUtils.rstring(),
                cseq: req.headers.cseq,
                'expires': '3600', 'Max-Forwards': 70
            }
        }, function (ret) {
            logger.info('---------------------end talk-------------------', ret);
            if (ret.status === 200) {

            } else {
                logger.info(ret);
            }
        });
    },
    getResponseXml(upperAccount) {
        let str = '<DeviceList Num="' + deviceCache.cameras.length + '">';
        for (let i = 0; i < deviceCache.cameras.length; i++) {
            const tmp = deviceCache.cameras[i];
            str += '<Item>' +
                '<DeviceID>' + config.SIP_CLIENT_PREFIX + '' + util.padding0(tmp.camera_id, 5) + '</DeviceID>' +
                '<Name>' + util.normalize(tmp.description) + '</Name>' +
                '<Manufacturer>' + util.normalize(tmp.brand) + '</Manufacturer>' +
                '<Model>NO</Model>' +
                '<Owner>0</Owner>' +
                '<CivilCode>340200</CivilCode>' +
                '<Address>' + util.normalize(tmp.crmcop.address) + '</Address>' +
                '<Parental>0</Parental>' +
                '<ParentID>' + upperAccount + '</ParentID>' +
                '<RegisterWay>1</RegisterWay>' +
                '<Secrecy>0</Secrecy>' +
                '<StreamNum>2</StreamNum>' +
                '<Status>ON</Status>' +
                '<Info>' +
                '<PTZType>3</PTZType>' +
                '<DownloadSpeed>1/2/4/8</DownloadSpeed>' +
                '</Info>' +
                '</Item>';
        }
        str += '</DeviceList>';
        return str;
    },
}
